//
//  JWCalendarViewController.m
//  SwitchCalendarPro
//
//  Created by sunjiawen on 2018/2/7.
//  Copyright © 2018年 sjw. All rights reserved.
//

#import "JWCalendarViewController.h"
#import "FSCalendar.h"
#import "JWCalendarCell.h"
#import "WXWaveView.h"
#import "UIView+Extension.h"
#import "UIViewController+LGSideMenuController.h"
#import "JWDatePickerView.h"
#import "SettingTurnNameViewController.h"
#import "JWAlarmListTableViewController.h"
#import "PresentingAnimator.h"
#import "DismissingAnimator.h"
#import "JWRealmManager.h"
#import "JWCalendarModel.h"

@interface JWCalendarViewController ()<FSCalendarDelegate,FSCalendarDataSource,FSCalendarDelegateAppearance,UIPopoverPresentationControllerDelegate,UIViewControllerTransitioningDelegate>
@property(nonatomic, strong) FSCalendar             *calendar;
@property(nonatomic, strong) WXWaveView             *waveView;
@property(nonatomic, strong) JWDatePickerView       *customPickerView;
@property(nonatomic, strong) JWCalendarModel        *calendarModel;
@property(nonatomic, strong) NSMutableArray         *dataSource;
@property(nonatomic, strong) NSArray                *currentTurnModelsEXChangesData;
@property(nonatomic, strong) NSString               *updateInfo;
@property(nonatomic, strong) UILabel                *titleLabel;
@property(nonatomic, strong) UILabel                *calendarNameLabel;

@property(nonatomic, strong) UIButton               *versionUpdateBtn;
@property(nonatomic, strong) NSDate                 *turnFirstDate;// 倒班的index==0的起始日期
@property(nonatomic, strong) NSDate                 *oldSelectedDate;
@property(nonatomic, assign) NSInteger              turnPeriod;// 周期 / 一个班组多少天

- (void)configureCell:(FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)position;

@end

@implementation JWCalendarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialData];
    
    [self setupUI];
    
    [self loadCalendarInfo];
    
    [self versionUpdate];
    
    // 创建或更新排班信息后
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(afterSettingNewTurnNotification) name:JWCalendarAfterCreatedOrUpdatedNotification object:nil];
    
    // 左边栏选择其他倒班
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(calendarListDidSelectedNotification:) name:JWCalendarListDidSelectedNotification object:nil];
    
    // 应用回到前台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActiveAction:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)initialData {
    // 从数据库里取出来的内容，如果默认的被删除了，则会自动取出数据库中的第一个日历，并设置为默认日历；数据库中没有内容则置为nil
    self.calendarModel = [[JWRealmManager defaultManager] queryCalendarDefault];
    
    [PublicData sharedInstance].currentSelectedCalendarId = self.calendarModel.calendarId;
}

- (void)setupUI {

    self.navigationController.navigationBar.translucent = NO;
    
    // 隐藏navigatonbar 分割线
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    
    // initial calendar
    CGFloat y = 0;
    self.calendar.frame = CGRectMake(0, y, self.view.bounds.size.width, calendarHeight);
    self.calendar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.calendar];

    // navigationItem titleView
    [self initalTitleView];
    
    // navigationBarButtonItem
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"排班" style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemAction:)];
    
    // navigationItem rightBarButtonItem
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"today"] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemAction:)];
    
    // waveView
    CGFloat waveY = CGRectGetMaxY(self.calendar.frame) + 80;
    CGFloat waveHeight = CGRectGetHeight(self.view.frame) - waveY;
    
    self.waveView = [WXWaveView addToView:self.view withFrame:CGRectMake(0, waveY, CGRectGetWidth(self.view.frame), waveHeight)];
    self.waveView.waveColor = MainBlueColor;
    self.waveView.backgroundColor = MainBlueColor;
    self.waveView.alpha = 1;
    self.waveView.waveSpeed = 3.5;
    self.waveView.angularSpeed = 1;
    
    [self.waveView wave];
    
    // 排班名
    self.calendarNameLabel = [[UILabel alloc]init];
    self.calendarNameLabel.backgroundColor = [UIColor clearColor];
    self.calendarNameLabel.font = [UIFont boldSystemFontOfSize:defaultFont + 15];
    self.calendarNameLabel.textColor = [UIColor whiteColor];
    self.calendarNameLabel.textAlignment = NSTextAlignmentLeft;
    self.calendarNameLabel.numberOfLines = 1;
    self.calendarNameLabel.layer.masksToBounds = NO;
    [self.calendarNameLabel setAdjustsFontSizeToFitWidth:YES];

    self.calendarNameLabel.alpha = 1;
    
    [self.view addSubview:self.calendarNameLabel];
    
    [self.calendarNameLabel makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.waveView.top).offset(25);
        make.left.equalTo(self.waveView.left).offset(20);
        make.width.lessThanOrEqualTo(200);
    }];
    
    
    [self addLeafBackground];
}

#pragma mark - Private
/**
 更新当前数据源信息
 */
- (void)loadCalendarInfo {
    
    self.calendarModel = [[JWRealmManager defaultManager] queryCalendarWithCalendarId:[PublicData sharedInstance].currentSelectedCalendarId];
    
    // 数据清空
    [self.dataSource removeAllObjects];
    self.turnPeriod = 0;
    self.turnFirstDate = nil;
    self.currentTurnModelsEXChangesData = nil;
    
    if (self.calendarModel != nil) {
        if (![self isBlankString:self.calendarModel.exchangedDate]) {
            self.currentTurnModelsEXChangesData = [[DateUtil dateUtilShareIntance]      getChangedDataByChangestr:self.calendarModel.exchangedDate];
        }
        for (JWScheduleModel *schedule in self.calendarModel.scheduleStatus) {
            [self.dataSource addObject:schedule];
        }
        // 设置倒班周期
        self.turnPeriod = self.dataSource.count;
        self.turnFirstDate = self.calendarModel.firstDate;
    }
    
    [self.calendar reloadData];
    [self updateCalendarName];
}

/**
 添加背景动画
 */
- (void)addLeafBackground {
    
    CAEmitterLayer *snowEmitter = [CAEmitterLayer layer];
    
    snowEmitter.emitterPosition = CGPointMake(self.view.bounds.size.width / 2.0, -30);
    snowEmitter.emitterSize  = CGSizeMake(self.view.bounds.size.width * 2.0, 0.0);
    snowEmitter.emitterShape = kCAEmitterLayerLine;
    snowEmitter.emitterMode  = kCAEmitterLayerOutline;
    
    CAEmitterCell *snowflake = [CAEmitterCell emitterCell];
    
    snowflake.birthRate    = 0.5;
    snowflake.lifetime    = 120.0;
    snowflake.velocity    = -30;
    snowflake.velocityRange = 20;
    snowflake.yAcceleration = 2;
    snowflake.emissionRange = 0.5 * M_PI;
    snowflake.spinRange = 0.25 * M_PI;
    snowflake.contents  = (id) [[UIImage imageNamed:@"snow"] CGImage];
    snowflake.color    = [[UIColor colorWithRed:0.600 green:0.658 blue:0.743 alpha:1.000] CGColor];
    
    snowEmitter.shadowOpacity = 1.0;
    snowEmitter.shadowRadius  = 0.0;
    snowEmitter.shadowOffset  = CGSizeMake(0.0, 1.0);
    snowEmitter.shadowColor   = [[UIColor whiteColor] CGColor];
    snowEmitter.emitterCells = [NSArray arrayWithObject:snowflake];
    [self.view.layer insertSublayer:snowEmitter atIndex:0];
    
    
}



- (void)versionUpdate{
    
    //获得当前发布的版本
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        //耗时的操作---获取某个应用在AppStore上的信息，更改id就行
        NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://itunes.apple.com/lookup?id=1221186861"]
                                                    encoding:NSUTF8StringEncoding error:nil];
        if (string == nil) {
            return;
        }
        NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
        if (data == nil) {
            return;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
            return;
        }
        
        //获得上线版本号
        NSString *version = [[[dic objectForKey:@"results"]firstObject]objectForKey:@"version"];
        
        _updateInfo = [[[dic objectForKey:@"results"]firstObject]objectForKey:@"releaseNotes"];
        
        //获得当前版本
        NSString *currentVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //更新界面
            
            if (version &&![version isEqualToString:currentVersion] && [currentVersion caseInsensitiveCompare:version] == NSOrderedAscending) {
                
                UIButton *updateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                [updateBtn setImage:[UIImage imageNamed:@"icon_version_update"] forState:UIControlStateNormal];
                [updateBtn addTarget:self action:@selector(updateBtnAction:) forControlEvents:UIControlEventTouchUpInside];
                [self.view addSubview:updateBtn];
                
                [updateBtn makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(self.waveView.top);
                    make.right.equalTo(-20);
                    make.width.height.equalTo(60);
                }];
                
            }else{
                //已是最高版本
                NSLog(@"已经是最高版本");
            }
        });
    });
}

- (void)updateBtnAction:(UIButton *)btn {
    //有新版本
    NSString *message = [NSString stringWithFormat:@"有新版本发布啦!\n%@",_updateInfo];
    
    UIAlertController *alertV = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *url = @"https://itunes.apple.com/cn/app/%E6%8E%92%E7%8F%AD%E5%B0%8F%E5%8A%A9%E6%89%8B-%E6%8E%92%E7%8F%AD%E6%97%A5%E5%8E%86-%E6%8A%A4%E5%A3%AB%E5%8C%BB%E7%94%9F%E5%80%92%E7%8F%AD%E5%BF%85%E5%A4%87/id1221186861?mt=8";
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
    }];
    
    [alertV addAction:cancelAction];
    [alertV addAction:updateAction];
    
    [self presentViewController:alertV animated:YES completion:nil];
}

- (void)updateCalendarName {
    if (self.calendarModel) {
        self.calendarNameLabel.text = self.calendarModel.calendarName;
    }else {
        self.calendarNameLabel.text = @"";
    }
}



- (void)configureVisibleCells
{
    [self.calendar.visibleCells enumerateObjectsUsingBlock:^(__kindof FSCalendarCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDate *date = [self.calendar dateForCell:obj];
        FSCalendarMonthPosition position = [self.calendar monthPositionForCell:obj];
        [self configureCell:obj forDate:date atMonthPosition:position];
    }];
}

- (void)configureCell:(FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    
    NSInteger differDaysCount = -1;
    NSInteger theDateInDataSourceIndex = -1;
    
    if (_turnFirstDate != nil && _turnPeriod > 0) {
        differDaysCount = [[DateUtil dateUtilShareIntance] getDaysFrom:_turnFirstDate To:date];
        theDateInDataSourceIndex = differDaysCount % _turnPeriod;
    }
    
    //    RoundModel *exchangeModel;
    //    if (_currentTurnModelsEXChangesData != nil && _currentTurnModelsEXChangesData.count > 0) {
    //        // 判断这一天是否为串休的日子 如果是则返回这一天应该是什么班
    //        exchangeModel = [[DateUtil dateUtilShareIntance] judeThisDateIsExchanged:date andExchanges:_currentTurnModelsEXChangesData];
    //    }
    
    if (differDaysCount >= 0) {// 正常按照排班顺序的话是否应该有班
        ((JWCalendarCell *)cell).dataModel = self.dataSource[theDateInDataSourceIndex];
        ((JWCalendarCell *)cell).oriDataModel = self.dataSource[theDateInDataSourceIndex];
        
        //        if (exchangeModel) {
        //            RoundModel *tempModel = self.dataSource[theDateInDataSourceIndex];
        //            if ([tempModel.name isEqualToString:exchangeModel.name]) {
        //                ((JWCalendarCell *)cell).chuanbanImageView.hidden = YES;
        //            }else {
        //                ((JWCalendarCell *)cell).chuanbanImageView.hidden = NO;
        //                ((JWCalendarCell *)cell).dataModel = exchangeModel;
        //            }
        //        }else {
        ((JWCalendarCell *)cell).chuanbanImageView.hidden = YES;
        //        }
        
    }else {
        ((JWCalendarCell *)cell).oriDataModel = nil;
        //        if (exchangeModel) {
        //            ((JWCalendarCell *)cell).chuanbanImageView.hidden = NO;
        //            ((JWCalendarCell *)cell).dataModel = exchangeModel;
        //        }else {
        ((JWCalendarCell *)cell).chuanbanImageView.hidden = YES;
        ((JWCalendarCell *)cell).dataModel = nil;
        //        }
        
    }
    //    NSLog(@"configureCell %@",date);
}

/**
 自定义NavigationBarTileView
 */
- (void)initalTitleView {
    CGFloat btnWithLabelMargin = 3.0f;
    CGFloat titleViewWidth = 200;
    CGFloat titleLabelWidth = 110;
    CGFloat titleLabelOriX = titleViewWidth/2.0 - titleLabelWidth/2.0;
    CGFloat btnWidth = 30;
    CGFloat prebtnOriginX = titleLabelOriX - btnWidth - btnWithLabelMargin;
    
    
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, titleViewWidth, 40)];
    titleView.backgroundColor = [UIColor clearColor];
    
    // 标题
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(titleLabelOriX, 0, titleLabelWidth, titleView.frame.size.height)];
    self.titleLabel.backgroundColor = [UIColor clearColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.font = [UIFont fontWithName:@"Futura-CondensedMedium" size:CalendarTitleFont];
    self.titleLabel.textColor = TitleColor;
    self.titleLabel.userInteractionEnabled = YES;
    self.titleLabel.text = [[DateUtil dateUtilShareIntance] dateToDateStr:self.calendar.currentPage withFormatter:@"yyyy年M月"];
    [titleView addSubview:self.titleLabel];
    
    self.navigationItem.titleView = titleView;
    
    CGFloat btnOriginY = self.titleLabel.center.y - btnWidth/2.0;
    
    UIButton *preBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    preBtn.frame = CGRectMake(prebtnOriginX, btnOriginY, btnWidth, btnWidth);
    [preBtn setImage:[UIImage imageNamed:@"cloud_left"] forState:UIControlStateNormal];
    [preBtn addTarget:self action:@selector(preMonth:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:preBtn];
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(CGRectGetMaxX(self.titleLabel.frame) + btnWithLabelMargin, btnOriginY, btnWidth, btnWidth);
    [nextBtn setBackgroundImage: [UIImage imageNamed:@"cloud_right"] forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextMonth:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:nextBtn];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseDate:)];
    [self.titleLabel addGestureRecognizer:tap];
}

#pragma mark - FSCalendarDelegate
- (void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated {
//    NSLog(@"ss,%@",NSStringFromCGRect(bounds));
    self.calendar.m_height = bounds.size.height;
    
    [self.calendar setCurrentPage:self.calendar.currentPage animated:YES];
    NSString *title = [[DateUtil dateUtilShareIntance] dateToDateStr:calendar.currentPage withFormatter:@"yyyy年M月"];
    self.titleLabel.text = title;
}

- (FSCalendarCell *)calendar:(FSCalendar *)calendar cellForDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    JWCalendarCell *cell = [calendar dequeueReusableCellWithIdentifier:@"calendarHomeCell" forDate:date atMonthPosition:monthPosition];

    return cell;
}


- (void)calendar:(FSCalendar *)calendar willDisplayCell:(FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition: (FSCalendarMonthPosition)monthPosition {
    [self configureCell:cell forDate:date atMonthPosition:monthPosition];

//    POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPViewScaleX];
//    anim.fromValue = @(0.0);
//    anim.toValue = @(1.0);
//    anim.springBounciness = 8;
//    anim.springSpeed = 4;
//
////    anim.duration = 0.3;
////    anim.beginTime = CACurrentMediaTime()+0.1;
//
//    [cell pop_addAnimation:anim forKey:@"animationkey"];
    
}

- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar {
    NSString *title = [[DateUtil dateUtilShareIntance] dateToDateStr:calendar.currentPage withFormatter:@"yyyy年M月"];
    self.titleLabel.text = title;
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    if (calendar.scope == FSCalendarScopeMonth) {
       
        
        JWCalendarCell *cell = (JWCalendarCell *)[calendar dequeueReusableCellWithIdentifier:@"calendarHomeCell" forDate:date atMonthPosition:monthPosition];
        
        BOOL isSecondSelected = NO;
        if (self.oldSelectedDate && self.oldSelectedDate == date) {
            isSecondSelected = YES;
        }
        
        self.oldSelectedDate = date;
        
        if (!isSecondSelected) {
            // 如果是第二次点击同一个item，则弹出串班
            return;
        }
        NSInteger differDaysCount = -1;
        NSInteger theDateInDataSourceIndex = -1;
        
        if (self.turnFirstDate != nil && self.turnPeriod > 0) {
            differDaysCount = [[DateUtil dateUtilShareIntance] getDaysFrom:self.turnFirstDate To:date];
            theDateInDataSourceIndex = differDaysCount % self.turnPeriod;
        }
        
//        RoundModel *exchangeModel;
//        if (_currentTurnModelsEXChangesData != nil && _currentTurnModelsEXChangesData.count > 0) {
//            // 判断这一天是否为串休的日子 如果是则返回这一天应该是什么班
//            exchangeModel = [[DateUtil dateUtilShareIntance] judeThisDateIsExchanged:date andExchanges:_currentTurnModelsEXChangesData];
//        }
        
        if (differDaysCount >= 0) {// 正常按照排班顺序的话是否应该有班
            cell.dataModel = self.dataSource[theDateInDataSourceIndex];
            cell.oriDataModel = self.dataSource[theDateInDataSourceIndex];
            
//            if (exchangeModel) {
//                RoundModel *tempModel = self.dataSource[theDateInDataSourceIndex];
//                if (![tempModel.name isEqualToString:exchangeModel.name]) {
//                    cell.dataModel = exchangeModel;
//                }
//            }
        }else {
            cell.oriDataModel = nil;
//            if (exchangeModel) {
//                cell.dataModel = exchangeModel;
//            }else {
                cell.dataModel = nil;
//            }
        }
        
        if (cell) {
            
        }
    }else if(calendar.scope == FSCalendarScopeWeek) {
       
    }

}

- (void)selectendNextItemPopoverChange {
    
    NSDate *date = [[DateUtil dateUtilShareIntance] theDayTomorrowDate:self.oldSelectedDate];
    self.oldSelectedDate = date;
    [self.calendar selectDate:date scrollToDate:YES];
    
    JWCalendarCell *cell = (JWCalendarCell *)[self.calendar dequeueReusableCellWithIdentifier:@"calendarHomeCell" forDate:date atMonthPosition:FSCalendarMonthPositionCurrent];
    
    if (cell) {
        NSInteger differDaysCount = -1;
        NSInteger theDateInDataSourceIndex = -1;
        
        if (_turnFirstDate != nil && _turnPeriod > 0) {
            differDaysCount = [[DateUtil dateUtilShareIntance] getDaysFrom:_turnFirstDate To:date];
            theDateInDataSourceIndex = differDaysCount % _turnPeriod;
        }
        
//        RoundModel *exchangeModel;
//        if (_currentTurnModelsEXChangesData != nil && _currentTurnModelsEXChangesData.count > 0) {
//            // 判断这一天是否为串休的日子 如果是则返回这一天应该是什么班
//            exchangeModel = [[DateUtil dateUtilShareIntance] judeThisDateIsExchanged:date andExchanges:_currentTurnModelsEXChangesData];
//        }
        
        if (differDaysCount >= 0) {// 正常按照排班顺序的话是否应该有班
            cell.dataModel = self.dataSource[theDateInDataSourceIndex];
            cell.oriDataModel = self.dataSource[theDateInDataSourceIndex];
            
//            if (exchangeModel) {
//                RoundModel *tempModel = self.dataSource[theDateInDataSourceIndex];
//                if (![tempModel.name isEqualToString:exchangeModel.name]) {
//                    cell.dataModel = exchangeModel;
//                }
//            }
        }else {
            cell.oriDataModel = nil;
//            if (exchangeModel) {
//                cell.dataModel = exchangeModel;
//            }else {
            cell.dataModel = nil;
//            }
        }
    }
}
#pragma mark - FSCalendarDataSource
- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date {
    return [[[DateUtil dateUtilShareIntance] chineseCalendarOfDate:date] string];
}

#pragma mark - FSCalendarDelegateAppearance
- (CGFloat)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance borderRadiusForDate:(NSDate *)date {
    return 0;
}

- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance titleDefaultColorForDate:(NSDate *)date {
    return [UIColor blackColor];
}

- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance titleSelectionColorForDate:(NSDate *)date {
    return [UIColor blackColor];
}


#pragma mark - Action
- (void)rightBarButtonItemAction:(UIBarButtonItem *)sender {
    [self.calendar setCurrentPage:[NSDate date] animated:YES];
    [self.calendar selectDate:[NSDate date]];
    
//    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"JWAlarm" bundle:nil];
//    if (storyboard) {
//        UINavigationController *nav = [storyboard instantiateViewControllerWithIdentifier:@"JWAlarmRootNavigationController"];
//        if (nav) {
//            nav.transitioningDelegate = self;
//            nav.modalPresentationStyle = UIModalPresentationCustom;
//            [self presentViewController:nav animated:YES completion:nil];
//        }
//    }
}

- (void)leftBarButtonItemAction:(UIBarButtonItem *)sender {

    [self.sideMenuController showLeftViewAnimated:YES completionHandler:nil];
}

- (void)nextMonth:(UIButton *)sender {
    [self.calendar setCurrentPage:[[DateUtil dateUtilShareIntance] nextMonth:self.calendar.currentPage] animated:YES];
}

- (void)preMonth:(UIButton *)sender {
    [self.calendar setCurrentPage:[[DateUtil dateUtilShareIntance] preMonth:self.calendar.currentPage] animated:YES];
}

/**
 选择并跳转至某天
 */
- (void)chooseDate:(UITapGestureRecognizer *)tap {
    
    [self.customPickerView pickerViewShow];
}

- (void)dateChanged:(id)sender{
    [self.calendar setCurrentPage:self.customPickerView.dataPicker.date animated:YES];
}

#pragma mark - Notification
/**
 监听创建完新的倒班表后的通知
 */
- (void)afterSettingNewTurnNotification {
    
    [self loadCalendarInfo];
    
}


/**
 监听选择新的倒班表的通知
 */
- (void)calendarListDidSelectedNotification:(NSNotification *)noti {
    NSString *selectedCalendarId = [noti object];
    
    if (selectedCalendarId == nil || [[PublicData sharedInstance].currentSelectedCalendarId isEqualToString:selectedCalendarId]) {
        return;
    }
    
    [PublicData sharedInstance].currentSelectedCalendarId = selectedCalendarId;
    [self loadCalendarInfo];

}

/**
 监听设置完串班后
 */
- (void)didExchangeTurnModelNotification:(NSNotification *)noti {
//    NSArray *newlocalDatas = [UserLocalUtil getTurnDatas];
//    if (newlocalDatas != nil && [newlocalDatas isKindOfClass:[NSArray class]]) {
//        [PublicData sharedInstance].allTurnDatas = [[NSMutableArray alloc]initWithArray:newlocalDatas];
//        if ([PublicData sharedInstance].currentTurnModel.localId == -1 || [PublicData sharedInstance].currentTurnModel == nil) {
//            [PublicData sharedInstance].currentTurnModel = [newlocalDatas firstObject];
//        }
//    }
//
//    [self updateTurnModels];
//    [self.calendar reloadData];
//    [self selectendNextItemPopoverChange];
//    [self updateCalendarName];
//    [self.colleagueView updateData];
//    [UserLocalUtil getDefaultTurnData];
//
//    [[NSNotificationCenter defaultCenter] postNotificationName:afterUpdateAllTurnDataNotificationKeys object:nil];
}

- (void)appDidBecomeActiveAction :(NSNotification *)noti {
    self.calendar.today = [NSDate date];
    [self.calendar reloadData];
}

#pragma mark - UIAdaptivePresentationControllerDelegate
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    // UIPopoverPresentationControllerDelegate,只有返回UIModalPresentationNone才可以让popover在手机上按照我们在preferredContentSize中返回的size显示。这是一个枚举，可以尝试换成其他的值尝试。
    return UIModalPresentationNone;
}

- (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController{
    //no点击蒙版popover不消失， 默认yes
    return YES;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Getter
- (FSCalendar *)calendar {
    if (!_calendar) {
        FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectZero];
        calendar.backgroundColor = [UIColor clearColor];
        calendar.delegate = self;
        calendar.dataSource = self;
        calendar.swipeToChooseGesture.enabled = YES;
        calendar.placeholderType = FSCalendarPlaceholderTypeNone;
        calendar.appearance.headerMinimumDissolvedAlpha = 0.4;
        calendar.appearance.separators = FSCalendarSeparatorNone;
        [calendar registerClass:[JWCalendarCell class] forCellReuseIdentifier:@"calendarHomeCell"];
        calendar.pagingEnabled = YES;// YES:横版 NO:竖版
        calendar.rowHeight = calendarHeight / 7;
        calendar.headerHeight = 0;
        calendar.weekdayHeight = 15;
        calendar.appearance.weekdayFont = [UIFont systemFontOfSize:10];
        calendar.appearance.weekendColor = MainBlueColor;
        calendar.appearance.weekdayTextColor = [UIColor lightGrayColor];
        [calendar selectDate:[NSDate date]];
        calendar.calendarWeekdayView.backgroundColor = [UIColor clearColor];
        _calendar = calendar;
    }
    return _calendar;
}

- (JWDatePickerView *)customPickerView {
    if (_customPickerView == nil) {
        _customPickerView = [[JWDatePickerView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        [_customPickerView.dataPicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:_customPickerView];
        
    }
    return _customPickerView;
}

- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - UIViewControllerTransitioningDelegate

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented
                                                                  presentingController:(UIViewController *)presenting
                                                                      sourceController:(UIViewController *)source
{
    return [PresentingAnimator new];
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [DismissingAnimator new];
}
@end
